package cn.lls.service.impl;

import cn.lls.base.result.R;
import cn.lls.base.result.ResultCode;
import cn.lls.base.common.LlsConstant;
import cn.lls.vo.oss.PolicyResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName OSSPolicyService
 * @Author 划水艺术家
 * @Date 2022/11/16 18:35
 * @Version 1.0
 **/

@Service
public class OSSPolicyService {

    @Autowired
    private OSS ossClient;

    public R policy(Integer model) {
        if (model < 0 || model >= LlsConstant.OSS_DIR.length){
            return R.fail(ResultCode.EXE_ERROR, "目录指定异常");
        }
        // 填写Host地址，格式为https://bucketname.endpoint。
        String host = "https://" + LlsConstant.BUCKETNAME + "." + LlsConstant.ENDPOINT;
        // 设置上传到OSS文件的前缀，yyyy-MM-dd，存储目录
        String dir = LlsConstant.OSS_DIR[model] + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        PolicyResult policyResult = new PolicyResult();
        try {
            long expireTime = 30;
            // 签名有效期
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            policyResult.setAccessId(LlsConstant.ACCESSKEYID);
            policyResult.setHost(host);
            policyResult.setPolicy(encodedPolicy);
            policyResult.setSignature(postSignature);
            policyResult.setExpire(String.valueOf(expireEndTime / 1000));
            policyResult.setDir(dir);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.success(policyResult);
    }
}
